import subprocess
import sys
import os

def check_python_version():
    """检查Python版本"""
    if sys.version_info < (3, 6):
        print("错误: 需要Python 3.6或更高版本")
        sys.exit(1)
    print(f"使用Python版本: {sys.version}")

def check_requirements():
    """检查并安装依赖"""
    print("检查Python依赖...")
    try:
        import flask
        import flask_cors
        import requests
        import dashscope
        print("所有依赖已安装")
    except ImportError as e:
        print(f"缺少依赖: {e}")
        print("正在安装依赖...")
        subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])
        print("依赖安装完成")
        
        # 再次检查是否成功安装
        try:
            import dashscope
            print("dashscope模块安装成功")
        except ImportError:
            print("警告: dashscope模块安装失败，请手动安装: pip install dashscope")
            print("或者使用以下命令安装所有依赖:")
            print("pip install -r requirements.txt")

def start_backend():
    """启动后端服务器"""
    print("正在启动Python后端服务器...")
    print("服务器将在 http://localhost:3002 上运行")
    print("按 Ctrl+C 停止服务器")
    print("-" * 50)
    
    try:
        # 启动Flask应用
        subprocess.call([sys.executable, "backend.py"])
    except KeyboardInterrupt:
        print("\n服务器已停止")
    except Exception as e:
        print(f"启动服务器时出错: {e}")

if __name__ == "__main__":
    print("=" * 50)
    print("时光相册 - Python后端服务器启动脚本")
    print("=" * 50)
    
    check_python_version()
    check_requirements()
    start_backend()